<?php
namespace Home\Controller;

use Think\Controller;

class AgentOnlineorderController extends SignInAgenController  //BaseController
{
    /*根据条件获取代理列表*/
    public function getAgen()
    {
        $upagenid = I('post.upagenid');//上级代理id
        $recommendId = I('post.recommendid');//发展人id
        $upagenAccount = I('post.upagenaccount');//上级代理账号
        $recommendAccount = I('post.recommendaccount');//发展人账号


    }

    //下级代理详细信息
    public function nextagen()
    {
        $id = I('post.id');
        $agen = M("agen")
            ->alias('a')
            ->join('agenlevel l ON l.level = a.level')
            ->where(array("a.id" => $id))
            ->field('a.*,l.name levelname')
            ->find();
        $level = $agen['level'];
        $agenstock = M('agenstock')
            ->alias("a")
            ->join("product p ON a.productId=p.id")
            ->where(array("a.agenId" => $id))
            ->field("a.*,p.name,p.price$level price,p.boxnum")
            ->select();
        $this->ajaxSuccess(array("agen" => $agen, "agenstock" => $agenstock));
    }

    /*根据条件获取一个代理 的详细信息 id or account*/
    private function getAgenOne($agenid = null, $account = null)
    {
        $page = I('post.page');
        $list = 20;
        $page2 = $page * $list;

        if ($agenid || $account) {
            $data = M('agen')
                ->alias("a")
                ->join("onlineorder o ON a.id=o.SourceId")
                ->where(array('a.upagenid' => $agenid, 'o.orderType' => 3))
                ->field("a.*,sum(o.total) sumbaodan")
                ->limit($page2, $list)
                ->group("o.SourceId")
                ->select();
            if ($data) {
                return $data;
            } else {
                return $this->ajaxError('没有你要的数据');
            }
        } else {
            return $this->ajaxError('没有你要的数据');

        }
    }

    /*根据代理id 获取所有下级代理*/
    private function getagenbyid($agenid)
    {
        $page = I('post.page');
        $list = 20;
        $page2 = $page * $list;

        if ($agenid) {
            $data = M('agen')
                ->alias("a")
                ->join("onlineorder o ON a.id=o.SourceId")
                ->where("o.orderType = 3 AND a.relation like '" . $agen['relation'] . ",%'")
                ->field("a.*,sum(o.total) sumbaodan")
                ->limit($page2, $list)
                ->group("o.SourceId")
                ->select();
            if ($data) {
                return $data;
            } else {
                return $this->ajaxError('无下级代理');
            }
        } else {
            return $this->ajaxError('代理人不存在');
        }
    }

    /*根据条件获取一个代理库存 详细信息*/
    public function agenstockbyagenid()
    {
        $id = parent::getagenAccountId();

        $data = M('agenstock')
            ->alias('a')
            ->join(' left join `product` b on a.productId=b.id')
            ->where(array('a.agenid' => $id))->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    /*获取某个代理的 代理申请 */
    public function getAgenreview()
    {
        // $id=I('post.id');//上级代理id
        $agenid = I('post.agenid');//代理id
        $data = M('agenreview')->where(array('agenid' => $agenid))->order('createtime desc')->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //审核代理
    public function auditagenreview()
    {
        $reviewid = I('post.id');

        // 没有ID
        if (empty($reviewid)) {
            $this->ajaxError("错误！");
        }

        // 代理审核
        $agenReview = M('AgenReview')->where(array('id' => $reviewid, "reviewid" => $this->getagenAccountId()))->find();

        // 如果有一个为空，异常
        if (empty($agenReview)) {
            return $this->ajaxError('数据异常！');
        }

        // 事务
        M()->startTrans();

        // 审核报单
        $msg = reportReview($agenReview['orderid'], true, false, "审核代理");

        // 如果失败
        if (!empty($msg)) {
            M()->rollback();
            $this->ajaxError($msg);
        }

        // 审核状态
        $r[] = M('AgenReview')->where(array('id' => $reviewid))->setField("status", 2);

        // 如果成功
        if (!in_array(false, $r)) {
            M()->commit();
            $this->ajaxSuccess("审核成功！");
        } else {
            M()->rollback();
            $this->ajaxError("审核失败！");
        }
    }

    // 代理申请流转
    public function flowagenreview()
    {
        $reviewid = I('id');//申请订单id
        $agenid = parent::getagenAccountId();

        $agenreview = M('agenreview')->where(array('id' => $reviewid, 'status' => 1, 'reviewId' => $agenid))->find();//获取申请 状态 2 类型 为2 升级类型
        if (!$agenreview) {
            return $this->ajaxError('审核信息不存在！');
        }
        $agen = M('agen')->where(array('id' => $agenreview['agenid']))->find();//申请的代理
        $reviewagen = M('agen')->where(array('id' => $agenreview['reviewid']))->find();//审核的代理
        $upagen = M('agen')->where(array('id' => $reviewagen['upagenid']))->find();//审核的代理 的上级
        $flow = M('flow')->where(array('sourceType' => 2, 'sourceId' => $agenreview['id']))->find();// 找到流转信息
        //$info = "代理审核流转上级";
        //没有流转信息，增加一条新的
        if (empty($flow)) {
            $flowdata = array(
                'sourceType' => 2//审核
            , 'sourceId' => $agenreview['id']
            , 'beforeId' => $agen['id']
            , 'afterId' => $reviewagen['id']
            , 'createTime' => now_datetime()
            , 'info' => "代理审核:由代理" . $agen['name'] . " " . $agen['account'] . "提交给" . $reviewagen['name'] . "审核"
            );
            $fadd = M('flow')->add($flowdata);
            if (!$fadd) {
                $this->ajaxError("保存流转记录失败");
            }
        }

        $updata = array('reviewId' => $upagen['id']);
        $updataOrder = array('toagenId' => $upagen['id']);
        //如果流转人 是1级代理 直接转至厂家
        if ($reviewagen['level'] == 1) {
            $updata['reviewId'] = 1;
            $updataOrder['toagenId'] = 1;
        }
        $res = M('agenreview')->where(array('id' => $reviewid, 'status' => 1))->setField($updata);
        $res2 = M('onlineorder')->where(array('id' => $agenreview['orderid'], 'status' => 1))->setField($updataOrder);

        if ($res && $res2) {
            $flowdata = array(
                'sourceType' => 2//代理审核
            , 'sourceId' => $agenreview['id']
            , 'beforeId' => $agenreview['reviewid']
            , 'afterId' => $updata['reviewId']
            , 'createTime' => now_datetime()
            , 'info' => "代理审核:由上级代理" . $agenreview['name'] . " " . $agenreview['account'] . "提交给" . $upagen['name'] . "审核"
            );
            M('flow')->add($flowdata);
            return $this->ajaxSuccess('操作完成');
        } else {
            return $this->ajaxError('操作失败');
        }
    }

    // 获取下级代理审核列表
    public function getdownreview()
    {
        $agenid = parent::getagenAccountId();

        $page = I('post.page');
        $list = 20;
        $page2 = $page * $list;
        $data = M('agenreview')
            ->alias('r')
            ->field('r.*, a.account,a.upagenid,a.upagenAccount,a.`name`,l.`name` levelname, case r.`status` when 1 then "待审核" when 2 then "代理已审核" when 3 then "厂家已审核" END stuname,case `type` when 1 then "注册" when 2 then "升级" END typename ')
            ->join(' LEFT JOIN agen a ON r.agenId = a.id LEFT JOIN agenlevel l ON l.`level` = a.`level`')
            ->where(array('reviewId' => $agenid))
            ->order('createtime desc')
            ->limit($page2, $list)
            ->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //  =====================  所有记录类接口  ==========================================================


    //获取所有下级代理
    public function getallagent()
    {
        $relation = I('post.relation');
        if (empty($relation)) {
            $relation = $this->getagenAccount()['relation'];
        }
        $id = $this->getagenAccountId();
        if (empty($id)) {
            $this->ajaxError("未登录");
        }
        $page = I('post.currentPage');
        $list = 20;
        if (!empty($relation)) {
            $data = M('agen')
                ->alias("a")
                ->join("left join onlineorder o ON a.id=o.SourceId AND o.orderType = 3 AND (o.`status` = 3 OR o.`status` = 1)")
                ->join("left join agenlevel l ON a.`level`=l.`level`")
                ->where("a.relation like '$relation%' and a.id != $id")
                ->field("a.*,IFNULL(sum(o.total),0) sumbaodan,l.`name` levelname")
                ->limit($page * $list, $list)
                ->group("a.id")
                ->select();
            if ($data) {
                return $this->ajaxSuccess($data);
            } else {
                return $this->ajaxError('无下级代理');
            }
        } else {
            return $this->ajaxError('代理人不存在');
        }
    }

    public function getallagent2()
    {
        $agenid = parent::getagenAccountId();
        $page = I('post.page');
        return $this->getagenbyid2($agenid, $page);
    }



    //  =====================  代理 （报单）订单处理==========================================================
    /*根据条件获取一个订单（报单）  ordertype 1 会员订单 2 代理订单 3 代理报单*/
    public function agenOrderbyorderid()
    {
        // $id=I('post.id');//上级代理id
        $orderid = I('post.id');// 代理id
        $ordertype = I('post.ordertype');//  1 会员订单 2 代理下单， 3代理报单
        $data = M('onlineorder')
            ->alias('a')
            ->join(' left join `orderdetails` b on a.id=b.orderid')
            ->where(array('a.id' => $orderid, 'a.ordertype' => $ordertype))->find();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //获取某代理报单列表
    public function getagenonlineorderlist()
    {
        $agenid = I('post.agenid');// 代理id
        $ordertype = I('post.ordertype');//  1 会员订单 2 代理下单， 3代理报单
        $pagesize = I('post.pagesize') ? 10 : I('post.pagesize');
        $pageindex = I('post.pageindex') ? 1 : I('post.pageindex');

        $data = M('onlineorder')
            ->alias('a')
            ->join(' left join `orderdetails` b on a.id=b.orderid')
            ->where(array('a.sourceid' => $agenid, 'a.ordertype' => $ordertype))
            ->order('createtime desc')
            ->page($pagesize, $pageindex)
            ->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //获取某代理报单 待审核的订单  列表
    public function getdauditagenonlineorderlist()
    {
        $agenid = I('post.agenid');// 代理id
        $ordertype = I('post.ordertype');//  1 会员订单 2 代理下单， 3代理报单
        $pagesize = I('post.pagesize') ? 10 : I('post.pagesize');
        $pageindex = I('post.pageindex') ? 1 : I('post.pageindex');
        $data = M('onlineorder')
            ->alias('a')
            ->join(' left join `orderdetails` b on a.id=b.orderid')
            ->where(array('a.sourceid' => $agenid, 'a.ordertype' => $ordertype))
            ->order('createtime desc')
            ->page($pagesize, $pageindex)
            ->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //我要报单
    public function addagenonlineorder()
    {
        $agen = $this->getagenAccount();
        $agenid = $this->getagenAccountId();
        //统计是否有审核报单未完成
        //onlineorder 状态2 驳回
        $rcount = M('agenreview')
            ->alias('r')
            ->join('onlineorder o on r.orderId = o.id AND o.status != 2')
            ->where("r.agenId = $agenid AND r.type = 2 AND r.`status` != 3")
            ->count();
        if ($rcount > 0) {
            $this->ajaxError('您已申请升级，请等待审核后重试！');
        }

        //报单等级
        $level = $agen['level'];
        //商品id和数量列表
        $products = I('post.products');
        $products = explode(",", $products);
        //购买商品列表
        if (empty($products)) {
            return $this->ajaxError('请先选择商品');
        }
        $allproductList = M("product")
            ->where(array('isUp' => 1, 'isDelete' => 2))
            ->select();
        //组合列表
        $productList = array();
        foreach ($allproductList as $product) {
            $newProduct = array($product["id"] => array(
                'id' => $product["id"],
                'name' => $product["name"],
                'img' => $product['img'],
                'price' => $product['price'],
                'price1' => $product['price1'],
                'price2' => $product['price2'],
                'price3' => $product['price3'],
                'price4' => $product['price4'],
                'price5' => $product['price5'],
                'price6' => $product['price6'],
                'price7' => $product['price7'],
                'price8' => $product['price8'],
                'price9' => $product['price9'],
                'price10' => $product['price10'],
                'deductible' => $product['deductible'],
                'bonus' => $product['bonus'],
                'bonus2' => $product['bonus2'],
                'introduce' => $product['introduce'],
                'boxnum' => $product['boxnum'],
                'rebate' => $product['rebate'],
                'myprice' => $product['price' . $level],
                'prozong' => 0,
                'num' => 0
            ));
            foreach ($newProduct as $key => $value) {
                $productList[$key] = $value;
            }
        }

        $buyList = array();
        $totalarray = array();
        //计算价格
        $total = 0;
        // 固定返利金额
        $rebatetotal = 0;
        $bonus = 0;
        $bonus2 = 0;

        if (!empty($products)) {
            for ($i = 0; $i < count($products); $i = $i + 2) {
                $id = $products[$i];
                $num = ceil($products[$i + 1]);
                if ($num <= 0 || $num > 99999) {
                    //数量小于等于0的不算
                    //$buyList[$id]['num'] = 0;
                } else {
                    //购买总价
                    $total += $productList[$id]['price' . $level] * $num;
                    $rebatetotal += $productList[$id]['rebate'] * $num;
                    $bonus += $total * $productList[$id]['bonus'] / 100;
                    $bonus2 += $total * $productList[$id]['bonus2'] / 100;
                    for ($j = 1; $j <= 10; $j = $j + 1) {
                        $totalarray[$j - 1] += $productList[$id]['price' . $j] * $num;
                    }
                    //存入数组
                    $buyList[$id] = $productList[$id];
                    $buyList[$id]['num'] = $num;
                }
            }
        }
        if (empty($buyList)) {
            return $this->ajaxError('请先选择商品');
        }

        $agenlevel = M('agenlevel')->where(array('level' => $level))->find();
        if ($total < $agenlevel['reportmoney']) {
            $this->ajaxError("报单价格不能低于最低拿货金额");
        }

        M()->startTrans();
        try {
            // 创建订单
            $order = array(
                'SourceId' => $agen['id'],
                'sn' => make_order_sn(),
                'orderType' => '3',//代理报单
                'payType' => '0',
                'toagenId' => $agen['upagenid'],
                'status' => '1',
                'total' => $total,
                'integral' => 0,
                'total1' => $totalarray[0],
                'total2' => $totalarray[1],
                'total3' => $totalarray[2],
                'total4' => $totalarray[3],
                'total5' => $totalarray[4],
                'total6' => $totalarray[5],
                'total7' => $totalarray[6],
                'total8' => $totalarray[7],
                'total9' => $totalarray[8],
                'total10' => $totalarray[9],
                'bonus' => $bonus,
                'bonus2' => $bonus2,
                'isFlow' => '2',
                'createTime' => now_datetime(),
                'updateTime' => now_datetime(),
                'phone' => $agen['phone'],
                'rebatetotal' => $rebatetotal
            );
            $orderId = M('onlineorder')->add($order);
            if (!$orderId) {
                M()->rollback();
                return $this->ajaxError('订单生成失败');
            }
            // 插入订单详细
            foreach ($buyList as $product) {
                $productId = $product['id'];
                $num = $product['num'];
                $price = $product['price' . $level];
                $ptotal = $num * $price;
                $boxnum = $product['boxnum'];
                $boxs = floor($num / $boxnum);
                if ($boxs >= 1) {
                    $nsstr = floor($num / $boxnum) . '箱' . $num % $boxnum . '盒';
                } else {
                    $nsstr = $num . '盒';
                }

                $orderProduct = array(
                    'orderId' => $orderId,
                    'productId' => $productId,
                    'num' => $num,
                    'price' => $price,
                    'total' => $ptotal,
                    'numShow' => $nsstr
                );
                $productDb = M('product')->where(array("id" => $productId))->find();
                if (empty($productDb) || $productDb['isDelete'] == 1) {
                    M()->rollback();
                    $this->ajaxError('商品ID' . $productId . '错误！');
                }

                $orderProductId = M('orderdetails')->add($orderProduct);

                // 如果出错
                if (!$orderProductId) {
                    M()->rollback();
                    $this->ajaxError("创建订单详细出错！");
                }
            }

            /*$recommid = $agen['recommendid'];
            $upid = $agen['upagenid'];
            if($recommid != $upid){
                $recommAgen = M('agen')
                    ->where("id = $recommid")
                    ->find();
                $rebate = $recommAgen['rebate'];
                if(empty($recommrebate) || $rebate==null){
                    //TODO 获取系统返佣比例 不对
                    $systemconfig = getConfig('site');
                    $rebate = $systemconfig['difference'];
                }
                //插入返佣表
                $diff = array(
                    'arrearsId' => $upid,
                    'accountId' => $recommid,
                    'sourceId' => $orderId,
                    'type' => 3,
                    'money' => $total*$rebate,
                    'status' => 1,
                    'createTime' => date("Y-m-d H:i:s"),
                    'updateTime' => date("Y-m-d H:i:s"),
                    'fromagenid' => $agen['id']
                );
                $diffId = M('difference')->add($diff);
                if(!$diffId){
                    M()->rollback();
                    $this->ajaxError("插入返佣表出错！");
                }
            }*/
            //推送消息
            $upagen = M('agen')->where(array('id' => $agen['upagenid']))->find();
            if ($upagen && $upagen['pushtag'] != null) {
                send_pub($upagen['pushtag'], "尊敬的：" . $upagen['account'] . "，下级代理" . $agen['account'] . "给您报单了，请注意及时审核哟");
            }
            // 提交
            M()->commit();
            return $this->ajaxSuccess('提交成功！请等待审核！');
        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }
    }

    //审核 下级代理报单 展示所有申请
    public function agenonlineorder()
    {
        $page = I('post.currentPage');
        $list = 20;
        $page2 = $page * $list;
        $agenId = parent::getagenAccountId();

        $status = I('post.status');
        //排除升级和注册
        if ($status == '' || $status == null || $status == 0) {
            $where = "o.toagenId = $agenId AND o.orderType = 3 AND r.orderId IS NULL";
        } else {
            if ($status == 3) {
                //已审核，显示3审核、2驳回
                $where = "o.toagenId = $agenId AND o.orderType = 3 AND r.orderId IS NULL AND (o.status = 3 OR o.status = 2)";
            } else {
                $where = "o.toagenId = $agenId AND o.orderType = 3 AND r.orderId IS NULL AND o.status = $status";
            }
        }
        //获取代理 需要审核的报单
        $agenorder = M('onlineorder')
            ->alias('o')
            ->join("LEFT JOIN agen ON o.SourceId=agen.id")
            ->join("LEFT JOIN agenlevel ON agen.level=agenlevel.level")
            ->join("LEFT JOIN agenreview r ON r.orderId = o.id")
            ->where($where)
            ->field("o.*,agen.account,agen.name agenname,agen.upagenAccount,agenlevel.name as levelname")
            ->order('o.createTime desc')
            ->limit($page2, $list)
            ->select();
        $agenstock = M('agenstock')
            ->alias('a')
            ->join("LEFT JOIN product ON a.productId=product.id")
            ->where(array('agenId' => $agenId))
            ->field("a.*,product.name,product.boxnum,product.flownum")
            ->select();
        return $this->ajaxSuccess(array('agenorder' => $agenorder, 'agenstock' => $agenstock));
    }

    //审核 下级代理报单
    public function auditdagenonlineorder()
    {
        $id = I('id');//订单id

        // 没有ID
        if (empty($id)) {
            $this->ajaxError("错误！");
        }

        try {
            M()->startTrans();

            // 审核报单
            $msg = reportReview($id);

            // 如果删除成功
            if (empty($msg)) {
                M()->commit();
                $this->ajaxSuccess("审核成功！");
            } else {
                M()->rollback();
                $this->ajaxError($msg);
            }

        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }
    }

    // 驳回 下级代理报单
    public function rejectReport()
    {
        if (IS_POST) {
            // 订单ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // 更新状态
            $r = M("OnlineOrder")->where(array("id" => $id))->save(array("status" => "2"));

            // 如果成功
            if ($r) {
                $this->ajaxSuccess("驳回成功！");
            } else {
                M()->rollback();
                $this->ajaxError("驳回失败！");
            }
        }
    }

    // 取消 我的代理报单
    public function cancelReport()
    {
        if (IS_POST) {
            // 订单ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }

            // 更新状态
            $r = M("OnlineOrder")->where(array("id" => $id))->save(array("status" => "5"));

            // 如果成功
            if ($r) {
                $this->ajaxSuccess("取消成功！");
            } else {
                M()->rollback();
                $this->ajaxError("取消失败！");
            }
        }
    }


    /**
     *代理报单 订单确认
     */
    /*public function confirmagenonlineorder()
    {
        $orderid = I('post.id');//订单id
        $agenId = I('post.uid');
        if(empty($agenId)){
            $agenId = parent::getagenAccountId();
        }
        $agenorder = M('onlineorder')->where(array('id' => $orderid, 'SourceId' => $agenId, 'status' => 3))->find();//获取到代理自己待确认（已发货）订单
        if (empty($agenorder)) {
            return $this->ajaxError('订单不存在');
        }
        M()->startTrans();
        try {
            $res = M('onlineorder')->where(array('id' => $orderid, 'SourceId' => $agenId, 'status' => 3))->save(array('status' => 4));
            if ($res) {
                $orderdtails = M('orderdetails')
                    ->where(array('orderId' => $orderid))
                    ->select();

                foreach ($orderdtails as $orderdtail) {
                    $agenstock = M('agenstock')->where(array('agenId' => $agenId, 'productId' => $orderdtail['productid']))->find();
                    if (empty($agenstock)) {//如果没有这个商品则 新添加这个商品的库存记录
                        M('agenstock')->add(array(
                            'agenId' => $agenId,
                            'productId' => $orderdtail['productid'],
                            'num' => 0
                        ));
                    }
                    $res = M('agenstock')->where(array('agenId' => $agenId, 'productId' => $orderdtail['productid']))->setInc('num', $orderdtail['num']);//添加库存
                    if ($res) {
                        M('stocklog')
                            ->add(array('sourceid' => $orderid, 'agenid' => $agenId, 'productid' => $orderdtail['productid'],
                                'numchange' => $orderdtail['num'], 'beforenum' => $agenstock['num'], 'afternum' => $agenstock['num'] + $orderdtail['num'],
                                'createtime' => now_datetime(), 'info' => '代理确认订单增加库存'
                            ));
                    }
                }

                //添加 发展人返佣
                if (!empty($agen['recommendid']) && $agen['recommendid'] != $agenorder['toagenid']) {
                    $recommend = M('agen')->where(array('id' => $agen['recommendid']))->find();//发展人
                    $upagen = M('agen')->where(array('id' => $agenorder['toagenid']))->find();// 上级代理人
                    $totalchange = $agenorder['total' . $upagen['level']] - $agenorder['total' . $recommend['level']];//上级代理跟发展人的订单额之差
                    if (!empty($totalchange) && $totalchange > 0 && $recommend['id'] != 1) {
                        $difference = $totalchange * getConfig('difference', 'difference');//0.5 系统可配置  1级代理的上级 为1级的话 固定返佣为10
                        if (!empty($recommend['rebate'])) {
                            $difference = $totalchange * $upagen['rebate'];//如果代理返佣 不为空 则使用代理自己的返佣
                        }
                        if ($agen['level'] == 1) {//报单人员等级为1
                            $difference = $agenorder['rebatetotal'];
                        }
                        $differencedb = array('arrearsId' => $upagen['id']
                        , 'accountId' => $recommend['id']
                        , 'sourceId' => $agenorder['sn']
                        , 'type' => 2//代理审核
                        , 'money' => $difference
                        , 'status' => '1'
                        , 'createTime' => now_datetime()
                        , 'fromagenid' => $agenId
                        );
                        M('difference')->add($differencedb);//插入返佣
                    }
                }
                M()->commit();
                return $this->ajaxSuccess('操作完成');
            } else {
                M()->rollback();
                return $this->ajaxError('操作失败');
            }
        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }
    }*/

    //
    /**
     *代理升级---待补充 报单
     */
    public function upgradeagen()
    {
        $agen = $this->getagenAccount();

        $aid = $agen['id'];
        //检查是否有提报的未完成的报单  有 不予升级；  无 可升级； 3报单 2审核
        $ordercount = M('onlineorder')
            ->where("(orderType = 2 OR orderType = 3) AND SourceId = $aid AND `status` != 3 AND `status` != 2")
            ->count();
        //$ordercount = M('onlineorder')->where(array('orderType' => 3, 'SourceId' => $agen['id'], 'status' => array('NEQ', 3), 'status' => array('NEQ', 2)))->count();
        if ($ordercount > 0) {
            return $this->ajaxError('尚有未完成的报单，不能升级代理级别');
        }
        $level = I('post.level');
        $products = I('post.products');
        $products = explode(',', $products);
        $money = I('post.zong');
        $syslevel = M('agenlevel')->where(array('level' => $level))->find();
        if (empty($syslevel)) {
            return $this->ajaxError('请选择代理级别');
        }
        if (empty($products)) {
            return $this->ajaxError('请先选择商品');
        }
        if ($money < $syslevel['money']) {
            return $this->ajaxError('升级金额不足');
        }
        $allproductList = M("product")
            ->where(array('isUp' => 1, 'isDelete' => 2))
            ->select();
        //组合列表
        $productList = array();
        foreach ($allproductList as $product) {
            $newProduct = array($product["id"] => array(
                'id' => $product["id"],
                'name' => $product["name"],
                'img' => $product['img'],
                'price' => $product['price'],
                'price1' => $product['price1'],
                'price2' => $product['price2'],
                'price3' => $product['price3'],
                'price4' => $product['price4'],
                'price5' => $product['price5'],
                'price6' => $product['price6'],
                'price7' => $product['price7'],
                'price8' => $product['price8'],
                'price9' => $product['price9'],
                'price10' => $product['price10'],
                'deductible' => $product['deductible'],
                'bonus' => $product['bonus'],
                'bonus2' => $product['bonus2'],
                'introduce' => $product['introduce'],
                'boxnum' => $product['boxnum'],
                'myprice' => $product['price' . $level],
                'prozong' => 0,
                'num' => 0
            ));
            foreach ($newProduct as $key => $value) {
                $productList[$key] = $value;
            }
        }
        $buyList = array();
        $totalarray = array();
        //计算价格
        $total = 0;
        $rebatetotal = 0;
        $bonus = 0;
        $bonus2 = 0;
        if (!empty($products)) {
            for ($i = 0; $i < count($products); $i = $i + 2) {
                $id = $products[$i];
                $num = ceil($products[$i + 1]);
                if ($num <= 0 || $num > 99999) {
                    //数量小于等于0的不算
                    //$buyList[$id]['num'] = 0;
                } else {
                    //购买总价
                    $total += $productList[$id]['price' . $level] * $num;
                    $rebatetotal += $productList[$id]['rebate'] * $num;
                    $bonus += $total * $productList[$id]['bonus'] / 100;
                    $bonus2 += $total * $productList[$id]['bonus2'] / 100;
                    for ($j = 1; $j <= 10; $j = $j + 1) {
                        $totalarray[$j - 1] += $productList[$id]['price' . $j] * $num;
                    }
                    //存入数组
                    $buyList[$id] = $productList[$id];
                    $buyList[$id]['num'] = $num;
                }
            }
        }

        if (empty($buyList)) {
            return $this->ajaxError('未选择商品');
        }

        M()->startTrans();
        try {
            // 创建订单
            $order = array(
                'SourceId' => $agen['id'],
                'sn' => make_order_sn(),
                'orderType' => '2',
                'payType' => '0',
                'toagenId' => $agen['upagenid'],
                'status' => '1',
                'total' => $total,
                'integral' => 0,
                'total1' => $totalarray[0],
                'total2' => $totalarray[1],
                'total3' => $totalarray[2],
                'total4' => $totalarray[3],
                'total5' => $totalarray[4],
                'total6' => $totalarray[5],
                'total7' => $totalarray[6],
                'total8' => $totalarray[7],
                'total9' => $totalarray[8],
                'total10' => $totalarray[9],
                'bonus' => $bonus,
                'bonus2' => $bonus2,
                'isFlow' => '2',
                'createTime' => now_datetime(),
                'updateTime' => now_datetime(),
                'phone' => $agen['phone'],
                'rebatetotal' => $rebatetotal
            );
//            for ( $j=0; $j<count($totalarray); $j=$j+1){
//                    $order['total'.$j+1]=$totalarray[$j];
//            }
            $orderId = M('onlineorder')->add($order);

            if (!$orderId) {
                M()->rollback();
                $this->ajaxError("创建订单出错！");
            }

            //插入审核表
            $agenreviewid = M('agenreview')->add(array(
                'agenId' => $agen['id'],
                "orderId" => $orderId,
                'level' => $syslevel['level'],
                'type' => 2,
                'money' => $total,
                'reviewId' => $agen['upagenid'],
                'status' => 1,
                'createTime' => now_datetime(),
                'regionId' => $agen['regionid'],
                'phone' => $agen['phone'],
                'webchat' => $agen['webchat']
            ));

            if (!$agenreviewid) {
                M()->rollback();
                $this->ajaxError("插入审核表出错！");
            }

            // 插入订单详细
            foreach ($buyList as $product) {
                $productId = $product['id'];
                $num = $product['num'];
                $price = $product['price' . $level];
                $ptotal = $num * $price;
                $boxnum = $product['boxnum'];
                $boxs = floor($num / $boxnum);
                if ($boxs >= 1) {
                    $nsstr = floor($num / $boxnum) . '箱' . $num % $boxnum . '盒';
                } else {
                    $nsstr = $num . '盒';
                }

                $orderProduct = array(
                    'orderId' => $orderId,
                    'productId' => $productId,
                    'num' => $num,
                    'price' => $price,
                    'total' => $ptotal,
                    'numShow' => $nsstr
                );

                $productDb = M('product')->where(array("id" => $productId))->find();

                if (empty($productDb) || $productDb['isDelete'] == 1) {
                    M()->rollback();
                    $this->ajaxError('商品ID' . $productId . '错误！');
                }

                $orderProductId = M('orderdetails')->add($orderProduct);

                // 如果出错
                if (!$orderProductId) {
                    M()->rollback();
                    $this->ajaxError("创建订单详细出错！");
                }
            }

            /*$recommid = $agen['recommendid'];
            $upid = $agen['upagenid'];
            if($recommid != $upid){
                $recommAgen = M('agen')
                    ->where("id = $recommid")
                    ->find();
                $rebate = $recommAgen['rebate'];
                if(empty($recommrebate) || $rebate==null){
                    //TODO 获取系统返佣比例 不对
                    $systemconfig = getConfig('site');
                    $rebate = $systemconfig['difference'];
                }
                //插入返佣表
                $diff = array(
                    'arrearsId' => $upid,
                    'accountId' => $recommid,
                    'sourceId' => $orderId,
                    'type' => 2,
                    'money' => $total*$rebate,
                    'status' => 1,
                    'createTime' => date("Y-m-d H:i:s"),
                    'updateTime' => date("Y-m-d H:i:s"),
                    'fromagenid' => $agen['id']
                );
                $diffId = M('difference')->add($diff);
                if(!$diffId){
                    M()->rollback();
                    $this->ajaxError("插入返佣表出错！");
                }
            }*/

            if ($orderId && $agenreviewid) {
                //推送消息
                $upagen = M('agen')->where(array('id' => $agen['upagenid']))->find();
                if ($upagen && $upagen['pushtag'] != null) {
                    send_pub($upagen['pushtag'], "尊敬的：" . $upagen['account'] . "，下级代理" . $agen['account'] . "提交了升级申请，请注意及时审核哟");
                }
                // 提交
                M()->commit();
                return $this->ajaxSuccess('提交成功');
            } else {
                M()->rollback();
                return $this->ajaxError('订单生成失败');
            }
        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }
    }

    //我的库存
    public function myagenstock()
    {
        $agenid = parent::getagenAccountId();

        $data = M('agenstock')
            ->alias('a')
            ->join(' left join `product` p on a.productId=p.id')
            ->field("a.*,p.`id` pid,p.`name`,p.introduce,p.img,p.price memprice,p.price1,p.price2,p.price3,p.price4,p.price5,p.price6,p.price7,p.price8,p.price9,p.price10,p.deductible,p.bonus,p.bonus2,p.boxnum,p.flownum
")
            ->where(array('a.agenid' => $agenid))->select();
        if ($data) {
            return $this->ajaxSuccess($data);
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //我的报单
    public function myagenonlineorderlist()
    {
        $page = I('currentPage');
        $list = 20;
        $page2 = $page * $list;
        // 代理
        $agenId = parent::getagenAccountId();

        //  1 会员订单 2 代理审核， 3代理报单
        $ordertype = 3;
        //$pagesize = I('pagesize') ? 10 : I('pagesize');
        //$pageindex = I('pageindex') ? 1 : I('pageindex');

        $status = I('post.status');
        //排除升级和注册
        if ($status == '' || $status == null || $status == 0) {
            $where = "o.Sourceid = $agenId AND o.orderType = $ordertype AND r.orderId IS NULL";
        } else {
            if ($status == 3) {
                //已审核，3审核、2驳回
                $where = "o.Sourceid = $agenId AND o.orderType = $ordertype AND r.orderId IS NULL AND (o.status = 3 OR o.status = 2)";
            } else {
                $where = "o.Sourceid = $agenId AND o.orderType = $ordertype AND r.orderId IS NULL AND o.status = $status";
            }
        }

        //获取代理的报单
        $agenorder = M('onlineorder')
            ->alias('o')
            ->join("LEFT JOIN agen a ON o.SourceId=a.id")
            ->join("LEFT JOIN agenlevel l ON a.level=l.level")
            ->join("LEFT JOIN agenreview r ON r.orderId = o.id")
            ->join("LEFT JOIN agen ua ON a.upagenid=ua.id")
            ->join("LEFT JOIN agenlevel ul ON ua.level=ul.level")
            ->where($where)
            ->field("o.*,a.account,a.name agenname,a.upagenAccount,l.name as levelname,ua.name upagenname,CASE ua.name WHEN '厂家' THEN '厂家' ELSE ul.name END upagenlevelname")
            ->order('o.createTime desc')
            ->limit($page2, $list)
            ->select();

        if ($agenorder) {
            return $this->ajaxSuccess(array('agenorder' => $agenorder));
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //报单详情
    public function myagenonlineorderdetail()
    {
        $orderid = I('orderid');
        // 当前代理
        $curagenid = parent::getagenAccountId();

        if (empty($curagenid)) {
            $this->ajaxError("未登录");
        }

        $flg = I('flg');
        // 自己的详情0 下级详情1
        if ($flg == 0) {
            $where = array('id' => $orderid, 'SourceId' => $curagenid);
        } else if ($flg == 1) {
            $where = array('id' => $orderid, 'toagenId' => $curagenid);
        }

        // 订单
        $onlineorder = M('onlineorder')
            ->where($where)
            ->find();
        if (empty($onlineorder)) {
            $this->ajaxError("此订单不存在！");
        }

        // 订单详情
        $detail = M('onlineorder')
            ->alias('a')
            ->field('a.id,a.sn,b.productId,c.name,b.total,b.price,b.num,c.boxnum')
            ->join(' left join `orderdetails` b on a.id=b.orderid left join product c on c.id = b.productId')
            ->where("a.id = $orderid")
            ->select();

        $agen = M('agen')
            ->alias('a')
            ->field('a.*,a.name username,b.name levelname,c.name upagenname,c.account upagenaccount,CASE c.name WHEN \'厂家\' THEN \'厂家\' ELSE d.name END upagenlevelname')
            ->join('left join agenlevel b on a.`level`=b.`level`')
            ->join('left join agen c on c.id=a.upagenid')
            ->join('left join agenlevel d on d.`level`=c.`level`')
            ->where(array('a.id' => $onlineorder['sourceid']))
            ->find();
        if ($detail) {
            return $this->ajaxSuccess(array('detail' => $detail, 'oorder' => $onlineorder, 'agen' => $agen, 'flg' => $flg));
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    //代理审核详情
    public function agenonlineorderdetail()
    {
        // 审核代理的id
        $reviewid = I('agenid');
        if (empty($reviewid)) {
            $reviewid = parent::getagenAccountId();
            $reviewagen = parent::getagenAccount();
        } else {
            $reviewagen = M('agen')
                ->where("id = $reviewid")
                ->find();
        }
        if (empty($reviewagen)) {
            $this->ajaxError("审核代理不存在！");
        }

        // 审核表id
        $viewid = I("viewid");

        // 订单id
        $orderid = I('orderid');
        // 订单
        $agenview = M('onlineorder')
            ->alias("a")
            ->join("left join agenreview r on r.orderId = a.id")
            ->field('a.*,r.`status` rvstatus,r.`level` rlevel')
            ->where(array('a.id' => $orderid, 'r.reviewId' => $reviewid))
            ->find();
        if (empty($agenview)) {
            $this->ajaxError("该订单不存在！");
        }

        // 代理库存
        $agenstock = M("agenstock")
            ->alias("a")
            ->join("product p ON a.productId=p.id")
            ->where(array('agenId' => $reviewid))
            ->field("p.name,a.*")
            ->select();

        // 商品数量
        $detail = M('onlineorder')
            ->alias('a')
            ->field('a.id,a.sn,b.productId,c.name,b.total,b.price,b.num,c.boxnum')
            ->join('left join `orderdetails` b on a.id=b.orderId left join product c on c.id = b.productId')
            ->where("a.id = $orderid")
            ->select();

        // 被审核代理id
        $agenid = I("agen");
        //被审核人
        $agen = M('agen')
            ->alias('a')
            ->field('a.*,a.name username,b.name levelname')
            ->join('left join agenlevel b on a.`level`=b.`level`')
            ->where("a.id = $agenid and find_in_set($reviewid,a.relation)>0")
            ->find();
        if ($detail) {
            return $this->ajaxSuccess(array('agenstock' => $agenstock, 'detail' => $detail, 'oorder' => $agenview, 'agen' => $agen, 'reviewagen' => $reviewagen, 'viewid' => $viewid));
        } else {
            return $this->ajaxError('没有你要的数据');
        }
    }

    // 驳回审核（升级、注册）
    public function rejectReview()
    {
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));

            // 没有ID
            if (empty($id)) {
                $this->ajaxError("id错误！");
            }

            $view = M('agenreview')->where(array('id' => $id))->find();

            if (empty($view)) {
                $this->ajaxError("审核信息错误！");
            }

            M()->startTrans();

            // 更新状态 4 驳回
            $vup = M("agenreview")->where(array("id" => $id))->save(array("status" => '4'));
            if (!$vup) {
                M()->rollback();
                $this->ajaxError("更新状态失败！");
            }

            // 更新状态为已驳回
            $oup = M("OnlineOrder")->where(array("id" => $view['orderid']))->save(array("status" => '2'));

            // 如果成功
            if ($oup) {
                M()->commit();
                $this->ajaxSuccess("驳回成功！");
            } else {
                M()->rollback();
                $this->ajaxError("驳回失败！");
            }
        }
    }

    //统计报单数量-APP用
    public function countOnlineorderStatus()
    {
        $agenId = parent::getagenAccountId();

        if (empty($agenId)) {
            $this->ajaxError("请登录！");
        }
        //排除升级和注册
        $where = "o.toagenId = $agenId AND o.orderType = 3 AND r.orderId IS NULL";

        //统计代理 需要审核的报单各状态数量
        $olSum = M('onlineorder')
            ->alias('o')
            ->join('LEFT JOIN agenreview r ON r.orderId = o.id')
            ->where($where)
            ->field('o.`status`,count(*) sums')
            ->group('o.`status`')
            ->select();
        $total = 0;
        foreach ($olSum as $v) {
            if ($v['status'] != 6) {
                $total += $v['sums'];
            }
        }
        $this->ajaxSuccess(array('statusSum' => $olSum, 'total' => $total));
    }

    //===============================代理 （下单）   订单管理===================================


    //获取代理所有的下单 记录
    public function getallagenDorder()
    {
        $agenid = I('agenid');//发展人id
        if ($agenid) {
            $data = M('agenorder')
                ->alias('a')
                ->join(' left join `product` b on a.productid=b.id')
                ->where(array('a.sourceid' => $agenid))->select();
            if ($data) {
                return $this->ajaxSuccess($data);
            } else {
                return $this->ajaxError('没有你要的数据');
            }
        } else {

            return $this->ajaxError('没有你要的数据');
        }
    }

    //获取代理所有的 接受的  下单记录
    public function getAlltoAgenOrder()
    {
        $page = I('currentPage');
        $list = 20;
        $page2 = $page * $list;
        $agenid = parent::getagenAccountId();

        if ($agenid) {
            $status = I('status');
            if ($status == '' || $status == null || $status == 0) {
                $where = array('a.toagenId' => $agenid);
            } else {
                $where = array('a.toagenId' => $agenid, 'a.status' => $status);
            }
            $agenorder = M('agenorder')
                ->alias('a')
                ->field('a.*,b.name name,b.boxnum,b.flownum,c.account,c.name agenname,a.name receivename,r.name_path namepath')
                ->join('left join `product` b on a.productId=b.id LEFT JOIN agen c on a.SourceId = c.id')
                ->join('left join region r on r.id = a.regionId')
                ->where($where)
                ->order('a.createTime desc')
                ->limit($page2, $list)
                ->select();

            if ($agenorder) {
                return $this->ajaxSuccess(array('agenorder' => $agenorder));
            } else {
                return $this->ajaxError('没有你要的数据');
            }
        } else {
            return $this->ajaxError('未登录');
        }
    }

    //  我要下单
    public function addagenorder()
    {
        $agen = $this->getagenAccount();
        $agenid = $this->getagenAccountId();
        //统计是否有审核报单未完成
        //onlineorder 状态2 驳回
        $rcount = M('agenreview')
            ->alias('r')
            ->join('onlineorder o on r.orderId = o.id AND o.status != 2')
            ->where("r.agenId = $agenid AND r.type = 2 AND r.`status` != 3")
            ->count();
        if ($rcount > 0) {
            $this->ajaxError('您已申请升级，请等待审核后重试！');
        }

        $productid = I('productid');
        $addressid = I('addressid');
        $productnum = ceil(I('num'));
        if ($productnum <= 0) {
            $this->ajaxError('请选择商品');
        }
        $agenaddress = M('agenaddress')->where(array('id' => $addressid, 'agenId' => $agenid))->find();
        if (empty($addressid) || empty($agenaddress)) {
            return $this->ajaxError('没有地址，请先输入地址在下单');
        }
        $product = M('product')->where(array('id' => $productid, 'isUp' => 1, 'isDelete' => 2))->find();
        if (empty($product)) {
            return $this->ajaxError('商品不存在');
        }
        $agenstock = M('agenstock')->where(array('agenId' => $agen['id'], 'productId' => $productid))->find();//库存
        if ($agenstock['num'] < $productnum) {
            return $this->ajaxError('商品库存不足');
        }
        $totalarray = array();
        $rebatetotal = 0;
        for ($j = 1; $j <= 10; $j = $j + 1) {
            $totalarray[$j - 1] += $product['price' . $j] * $productnum;
            $rebatetotal = $product['rebate'] * $productnum;
        }
        $total = $product['price' . $agen['level']] * $productnum;
        $bonus = $total * $product['bonus'];
        $bonus2 = $total * $product['bonus2'];
        $boxnum = $product['boxnum'];
        $boxs = floor($productnum / $boxnum);
        if ($boxs >= 1) {
            $nsstr = floor($productnum / $boxnum) . '箱' . $productnum % $boxnum . '盒';
        } else {
            $nsstr = $productnum . '盒';
        }

        M()->startTrans();
        try {
            // 创建订单
            $order = array(
                'SourceId' => $agen['id'],
                'sn' => make_order_sn(),
                'productId' => $productid,
                'num' => $productnum,
                'price' => $product['price' . $agen['level']],
                'orderType' => '3', //订单
                'payType' => '3', //库存
                'toagenId' => $agen['upagenid'],
                'agenId' => $agenid,
                'status' => '2',
                'total' => $total,
                'integral' => 0,
                'total1' => $totalarray[0],
                'total2' => $totalarray[1],
                'total3' => $totalarray[2],
                'total4' => $totalarray[3],
                'total5' => $totalarray[4],
                'total6' => $totalarray[5],
                'total7' => $totalarray[6],
                'total8' => $totalarray[7],
                'total9' => $totalarray[8],
                'total10' => $totalarray[9],
                'bonus' => $bonus,
                'bonus2' => $bonus2,
                'isFlow' => '2',
                'createTime' => now_datetime(),
                'updateTime' => now_datetime(),
                'regionId' => $agenaddress['regionid'],
                'name' => $agenaddress['name'],
                'phone' => $agenaddress['phone'],
                'address' => $agenaddress['address'],
                'rebatetotal' => $rebatetotal,
                'numShow' => $nsstr
            );
            $orderId = M('agenorder')->add($order);
            if (!$orderId) {
                M()->rollback();
                return $this->ajaxError('订单生成失败');
            } else {
                /*$orderProduct = array(
                    'orderId' => $orderId,
                    'productId' => $productid,
                    'num' => $productnum,
                    'price' => $product['price' . $agen['level']],
                    'total' => $total
                );
                $orderProductId = M('orderdetails')->add($orderProduct);
                // 如果出错
                if (!$orderProductId) {
                    M()->rollback();
                    $this->ajaxError("创建订单详细出错！");
                }*/

                //扣除下单人库存  并添加记录
                $res = M('agenstock')->where(array('agenId' => $agen['id'], 'productId' => $productid))->setDec('num', $productnum);//扣库存
                if ($res) {
                    $slog = M('stocklog')->add(array(
                        'sourceid' => $orderId
                    , 'agenid' => $agen['id']
                    , 'productid' => $productid
                    , 'numchange' => $productnum
                    , 'beforenum' => $agenstock['num']
                    , 'afternum' => $agenstock['num'] - $productnum
                    , 'createtime' => now_datetime()
                    , 'info' => '代理下单扣除库存'
                    ));
                    if (!$slog) {
                        M()->rollback();
                        $this->ajaxError("创建库存记录出错！");
                    }
                }
            }
            //推送消息
            $upagen = M('agen')->where(array('id' => $agen['upagenid']))->find();
            if ($upagen && $upagen['pushtag'] != null) {
                send_pub($upagen['pushtag'], "尊敬的：" . $upagen['account'] . "，下级代理" . $agen['account'] . "给您下单了，请注意及时发货哟");
            }
            M()->commit();
            return $this->ajaxSuccess('下单成功');
        } catch (\Exception $e) {
            // 回滚
            M()->rollback();
            $this->ajaxError("处理失败！");
        }
    }

    //  下单发货
    public function editagenorder()
    {
        $orderid = I('id');//订单号码
        $logisticsCom = I('code');//物流公司编码
        $logistics = I('logistics');//物流单号
        if (empty($logistics)) {
            $this->ajaxError("请输入物流单号！");
        }
        if (empty($logisticsCom)) {
            $this->ajaxError("请输入物流公司！");
        }

        $tracingSns = parent::get('tracingSns');
        $res = send($orderid, $logisticsCom, $logistics, $tracingSns);
        if (!empty($tracingSns)) {
            //清空
            parent::remove('tracingSns');
            parent::remove('uptrac');
            parent::remove('tracinfo');
            parent::remove('sel');
        }
        if ($res == "") {
            $this->ajaxSuccess("发货完成！");
        } else {
            $this->ajaxError("发货失败！");
        }
    }

    // 代理下单流转上级
    public function flowAgenOrder()
    {
        // 流转至厂家1或上级2
        //$type = I('type');
        $orderid = I('orderid');// 订单id
        $agenid = parent::getagenAccountId();

        $agenorder = M('agenorder')->where(array('id' => $orderid, 'status' => 2, 'toagenId' => $agenid))->find();//获取申请 状态 2 类型 为2 升级类型
        if (!$agenorder) {
            return $this->ajaxError('订单信息获取失败！');
        }
        $agen = M('agen')->where(array('id' => $agenorder['sourceid']))->find();//申请的代理
        $reviewagen = M('agen')->where(array('id' => $agenorder['toagenid']))->find();//审核的代理
        $upagen = M('agen')->where(array('id' => $reviewagen['upagenid']))->find();//审核的代理 的上级
        $flow = M('flow')->where(array('sourceType' => 1, 'sourceId' => $orderid))->find();// 找到流转信息
        //$info = "代理下单流转上级";
        //没有流转信息，增加一条新的
        if (empty($flow)) {
            $flowdata = array(
                'sourceType' => 1//下单
            , 'sourceId' => $agenorder['id']
            , 'beforeId' => $agen['id']
            , 'afterId' => $reviewagen['id']
            , 'createTime' => now_datetime()
            , 'info' => "代理下单:由代理" . $agen['name'] . " " . $agen['account'] . "提交给" . $reviewagen['name'] . "审核"
            );
            $fadd = M('flow')->add($flowdata);
            if (!$fadd) {
                $this->ajaxError("保存流转记录失败");
            }
        }
        $updata = array('toagenId' => $upagen['id'], 'isFlow' => 1);
        if ($reviewagen['level'] == 1) {//如果流转人 是1级代理 直接转厂家
            $updata['toagenId'] = 1;
        }
        /*if($type == 1){
            $updata = array( 'toagenId' => 1,'isFlow' => 1);
            $info = "代理下单流转厂家";
        } else {
            $upagen = M('agen')->where(array('id' => $reviewagen['upagenid']))->find();//审核的代理 的上级
            $updata = array( 'toagenId' => $upagen['id'],'isFlow' => 1);
            if ($reviewagen['level'] == 1) {//如果流转人 是1级代理 直接转厂家
                $updata['toagenId'] = 1;
            }
        }*/
        $res = M('agenorder')
            ->where(array('id' => $orderid, 'status' => 2))
            ->save($updata);
        if ($res) {
            $flowdata = array(
                'sourceType' => 1//下单
            , 'sourceId' => $agenorder['id']
            , 'beforeId' => $reviewagen['id']
            , 'afterId' => $updata['toagenId']
            , 'createTime' => now_datetime()
            , 'info' => "代理下单:由上级代理" . $reviewagen['name'] . " " . $reviewagen['account'] . "提交给" . $upagen['name'] . "审核"
            );
            $fadd = M('flow')->add($flowdata);
            if (!$fadd) {
                $this->ajaxError("保存流转记录失败");
            }
            $this->ajaxSuccess('操作完成');
        } else {
            $this->ajaxError('操作失败');
        }
    }

    //  下单 确认
    public function confirmagenorder()
    {
        $orderid = I('id');
        $agenid = parent::getagenAccountId();

        if (empty($orderid)) {
            return $this->ajaxError('无效订单号');
        }
        //根据订单id查询订单
        $orderdata = M('agenorder')->where(array('id' => $orderid, 'SourceId' => $agenid))->find();
        if (!$orderdata) {
            return $this->ajaxError('订单不存在');
        }
        $res = M('agenorder')->where(array('id' => $orderid, 'SourceId' => $agenid))->save(array('status' => 4));
        if ($orderdata['toagenid'] != 1) {//如果不是厂家发货则给发货代理添加库存
            $toagenstock = M('agenstock')->where(array('agenId' => $orderdata['toagenid'], 'productId' => $orderdata['productid']))->find(); //代理商库存
            $rest = M('agenstock')->where(array('agenId' => $orderdata['toagenid'], 'productId' => $orderdata['productid']))->setInc('num', $orderdata['num']);//增加库存
            if ($rest) {
                M('stocklog')
                    ->add(array('sourceid' => $orderid, 'agenid' => $agenid, 'productid' => $orderdata['productid'],
                        'numchange' => $orderdata['num'], 'beforenum' => $toagenstock['num'], 'afternum' => $toagenstock['num'] + $orderdata['num'],
                        'createtime' => now_datetime(), 'info' => '代理确认订单，发货代理增加库存'
                    ));
            }
        }
        if ($res) {
            return $this->ajaxSuccess('操作完成');
        } else {
            return $this->ajaxError('操作失败');
        }
    }

    //扫描溯源码
    public function addtracing()
    {
        $tracingsn = I('tracingsn');
        //$orderid = I('id');
        $agen = $this->getagenAccount();

        if (empty($agen)) {
            $this->ajaxError("用户未登录！");
        }
        if (strlen($tracingsn) == 0 || $tracingsn == null || $tracingsn == '') {
            $this->ajaxError("溯源码不存在！");
        } else {
            $tracing = M('tracing')->where(array('sn' => $tracingsn))->find();
        }
        if (empty($tracing)) {
            $this->ajaxError("溯源码不存在！");
        }

        //获取通用信息
        $sel = parent::get('sel');
        $compnum = $sel['compnum'];
        $orderid = $sel['order']['id'];

        $agenacc = $sel['agenacc'];
        $agenid = $sel['agenid'];
        //无数据获取流转到的代理并保存
        if (empty($agenacc) && empty($agenid)) {
            $agenorder = M('agenorder')
                ->alias('a')
                ->join('left join agen b on a.SourceId=b.id')
                ->join('left join agen c on a.toagenId=c.id')
                ->field('a.*,b.id as bid,b.account as baccount,b.level as blevel ,c.id as cid,c.account as caccount ,c.level as clevel')
                ->where(array('a.id' => $orderid))->find();
            $agenacc = $agenorder['baccount'];
            $agenid = $agenorder['bid'];
        }

        /*//第一次扫码
        if (empty($tracing['tracingflow'])) {
            $tracingflow =   '1,' . $agenorder['toagenid'];
            $tracingflowinfo = '厂家 > ' . getagentlevel($agenorder['clevel']) . '(' . $agenorder['caccount'] . ')';
            $res3 = M('flow')->add(array(
                'sourceType' => 3,
                'sourceId' => $tracing['id'],
                'beforeId' => $agenorder['toagenid'],
                'afterId' => $agenorder['sourceid'],
                'createTime' => now_datetime(),
                'info' => '溯源流转信息记录'
            ));
            $res4 = M('tracing')->where(array('id' => $tracing['id']))->setField(array('tracingflow' => $tracingflow,
                'tracingflowInfo' => $tracingflowinfo
            ));
        }
        $flow = M('flow')->where(array('sourceType' => 3, 'sourceId' => $tracing['id'], 'beforeId' => $agen['id']))->find();//溯源流转
        $orderflows = M('flow')->where(array('sourceType' => 1, 'sourceId' => $orderid))->order('createTime')->select();
        if (empty($flow)) {//判断是否已经扫过
            if (empty($orderflows)) { //是否流转过   这是未流转的
                $sflow = M('flow')
                    ->alias('f')
                    ->join('left join agen a on f.afterId=a.id ')
                    ->field('f.* , a.account,a.level')
                    ->where(array('f.sourceType' => 3, 'f.sourceId' => $tracing['id']))->order('f.createTime desc')->limit(1)->find();

                $res1 = M('flow')->add(array(
                    'sourceType' => 3,
                    'sourceId' => $tracing['id'],
                    'beforeId' => $agenorder['toagenid'],
                    'afterId' => $agenorder['sourceid'],
                    'createTime' => now_datetime(),
                    'info' => '溯源流转信息记录'
                ));
                $agentleve = getagentlevel($agen['level']);
                $agenmsg = $agen['account'] . '(' . $agentleve . ')';
                $res2 = M('tracing')->where(array('id' => $tracing['id']))->setField(array('tracingflow' => $tracing['tracingflow'] . ',' . $agen['id'],
                    'tracingflowinfo' => $tracing['tracingflowinfo'] . '>' . $agenmsg
                ));
            } else {//这是 流转的
                foreach ($orderflows as $orderflow) {
                    $sflow2 = M('flow')
                        ->where(array('sourceType' => 3, 'sourceId' => $tracing['id'], 'afterId' => $orderflow['afterid']))->order('createTime desc')->limit(1)->find();
                    if (empty($sflow2)) {
                        M('flow')->add(array(
                            'sourceType' => 3,
                            'sourceId' => $tracing['id'],
                            'beforeId' => $orderflow['afterid'],
                            'afterId' => $orderflow['beforeid'],
                            'createTime' => now_datetime(),
                            'info' => '溯源流转信息记录'
                        ));
                        $agentflow = M('agen')->where(array('id' => $orderflow['beforeid']))->find();
                        $agentleve = getagentlevel($agentflow['level']);
                        $agenmsg = $agentflow['account'] . '(' . $agentleve . ')';
                        M('tracing')->where(array('id' => $tracing['id']))->setField(array('tracingflow' => $tracing['tracingflow'] . ',' . $orderflow['afterId'],
                            'tracingflowinfo' => $tracing['tracingflowinfo'] . '>' . $agenmsg
                        ));
                    }
                }
            }
        }*/


        //获取溯源信息
        $tracflg = 0;
        $msg = "扫描成功";
        $tracing = M('tracing')->where(array('sn' => $tracingsn))->find();
        $tracflow = $tracing['tracingflow'];
        if (!empty($tracflow)) {
            //有流转信息
            //遍历存入原流转信息
            $tracflows = explode(",", $tracflow);
            $tracaccount = array();
            for ($i = 0; $i < count($tracflows); $i++) {
                //已流转过
                if ($tracflows[$i] == $agenid) {
                    $tracflg = 1;
                    break;
                }
                if ($tracflows[$i] != '') {
                    if ($tracflows[$i] == 1) {
                        $tracaccount[$i] = '厂家';
                    } else {
                        $tagen = M('agen')->where("id = $tracflows[$i]")->find();
                        if (!in_array($tagen['account'], $tracaccount)) {
                            $tracaccount[$i] = $tagen['account'];
                        }
                    }
                }
            }
            //最后存入下级代理
            $tracaccount[count($tracflows)] = $agenacc;
        } else {
            //无流转信息，存入代理
            $tracaccount[0] = $agen['account'];
            $tracaccount[1] = $agenacc;
        }

        if (empty($tracaccount)) {
            $this->ajaxError("溯源信息错误！");
        }
        //读取溯源数组
        $uptrac = parent::get('uptrac');
        $tracinfos = parent::get('tracinfo');
        $tracingSns = parent::get('tracingSns');
        if ($uptrac == null || $uptrac == 'null' || $compnum == 0) {
            parent::remove('uptrac');
            parent::remove('tracinfo');
            parent::remove('tracingSns');
            $uptrac = array();
            $tracinfos = array();
            $tracingSns = array();
        }
        if (array_key_exists($tracingsn, $uptrac) || $tracflg == 1) {
            //重复扫描，数目不减
            $msg = "请不要重复扫描！";
        } else {
            $uptrac[$tracingsn] = $tracing['tracingflow'] . ',' . $agen['id'];
            $tracing['flowlist'] = $tracaccount;
            $tracinfos[$compnum] = $tracing;
            $tracingSns[$compnum] = $tracingsn;
        }
        parent::set('uptrac', $uptrac);
        parent::set('tracinfo', $tracinfos);
        parent::set('tracingSns', $tracingSns);
        $compnum = sizeof($uptrac);
        $sel['compnum'] = $compnum;
        $sel['agenacc'] = $agenacc;
        $sel['agenid'] = $agenid;
        parent::set('sel', $sel);

        //记录流转flow  sourcetype=3 为溯源信息

        if ($tracing) {
            $this->ajaxSuccess(array('sel' => $sel, 'tracinfo' => $tracinfos, 'msg' => $msg));
        } else {
            $this->ajaxError("添加失败！");
        }
    }

    //溯源扫码页面初始化
    public function seltracing()
    {
        $compnum = 0;
        $agenid = parent::getagenAccountId();

        $orderid = I('id');
        $order = M('agenorder')
            ->alias('a')
            ->join("product p ON a.productId=p.id")
            ->where(array('a.id' => $orderid, 'a.toagenId' => $agenid))
            ->field("a.*,p.name,p.boxnum")
            ->find();
        if ($order) {
            parent::set('sel', array('order' => $order, 'compnum' => $compnum));
            $this->ajaxSuccess(array('order' => $order, 'compnum' => $compnum));
        } else {
            $this->ajaxError("查询失败！");
        }
    }


    //todo  溯源码列表
    public function gettracinglist()
    {


    }

    // 订单管理
    public function myOrder()
    {
        $page = I('currentPage');
        $list = 20;
        $page2 = $page * $list;
        $agenid = parent::getagenAccountId();

        $status = I('post.status');
        if ($status == '' || $status == null || $status == 0) {
            $where = array('SourceId' => $agenid);
        } else {
            $where = array('SourceId' => $agenid, 'a.status' => $status);
        }
        $orderdata = M('agenorder')
            ->alias("a")
            ->join("left join product ON a.productId=product.id ")
            ->join("left join agen ON a.toagenId=agen.id")
            ->join("left join region r on r.id = a.regionId")
            ->where($where)
            ->field("a.*,product.name,agen.account,agen.name agenname,a.name receivename,r.name_path namepath")
            ->order('createTime desc')
            ->limit($page2, $list)
            ->select();

        return $this->ajaxSuccess($orderdata);
    }

    //统计报单数量-APP用
    public function countAgenorderStatus()
    {
        $agenid = parent::getagenAccountId();

        $aoSum = M('agenorder')
            ->where(array('toagenId' => $agenid))
            ->field("`status`,count(*) sums")
            ->group('`status`')
            ->select();
        $total = 0;
        foreach ($aoSum as $v) {
            if ($v['status'] != 1) {
                $total += $v['sums'];
            }
        }
        $this->ajaxSuccess(array('statusSum' => $aoSum, 'total' => $total));
    }

    //会员订单
    public function memOrder()
    {
        $page = I('post.page');
        $list = 20;
        $page2 = $page * $list;
        $status = I('post.status');
        $agenid = parent::getagenAccountId();

        if ($status == '' || $status == null || $status == 0) {
            $where = "o.toagenId = $agenid and o.orderType = 1";
        } else {
            $where = "o.toagenId = $agenid and o.orderType = 1 and o.status = $status";
        }
        $data = M('onlineorder')
            ->alias('o')
            ->join('left join member m on o.SourceId = m.id')
            ->join('region r on r.id = o.regionId')
            ->where($where)
            ->field('o.*,m.account memberaccount,m.name membername,o.name receivename,r.name_path namepath')
            ->order('o.createTime desc')
            ->limit($page2, $list)
            ->select();
        foreach ($data as $k => $v) {
            $order_id = $v['id'];
            $data[$k]['goods'] = M('orderdetails')
                ->alias("o")
                ->join("LEFT JOIN product p on o.productId = p.id")
                ->where("o.orderid='$order_id'")
                ->field("o.*,p.`name`,p.introduce,p.img,p.price memprice,p.price1,p.price2,p.price3,p.price4,p.price5,p.price6,p.price7,p.price8,p.price9,p.price10,p.deductible,p.bonus,p.bonus2,p.boxnum,p.flownum
")
                ->select();
        }
        return $this->ajaxSuccess($data);
    }

    //订单驳回
    public function cancel()
    {
        $agenid = parent::getagenAccountId();

        $id = I("id");
        if (empty($id)) {
            $this->ajaxError("订单ID为空");
        }

        M()->startTrans();

        // 更新订单状态
        $ok = M('onlineorder')
            ->where(array('id' => $id, 'toagenId' => $agenid, 'status' => '1'))
            ->save(array('status' => '6'));

        if (!$ok) {
            M()->rollback();
            $this->ajaxError("订单驳回失败");
        }

        $order = M('onlineorder')->where(array("id" => $id, "toagenId" => $agenid))->find();
        $ointegral = $order['integral'];
        // 订单积分大于0，返还积分
        if (!empty($ointegral) && $ointegral != null && $ointegral > 0) {
            $memberId = $order['sourceid'];
            $member = M('member')->where("id = $memberId")->find();
            $chintegral = $member['integral'] + $ointegral;
            //更新会员积分-返还积分
            $mok = M('member')
                ->where(array("id" => $memberId))
                ->save(array("integral" => $chintegral));
            if (!$mok) {
                M()->rollback();
                $this->ajaxError("返还积分失败");
            }
        }

        M()->commit();
        $this->ajaxSuccess("订单已驳回");
    }

    // 准备报单页面
    public function getStockAndProductInfo()
    {
        $agen = $this->getagenAccount();

        $agenId = $agen['id'];
        $level = $agen['level'];
        //商品库存列表
        $products = M("product")
            ->alias('p')
            ->join(" LEFT JOIN (SELECT * from agenstock WHERE agenId = $agenId) a ON a.productId = p.id")
            ->field("a.id sid,a.agenId,ifnull(a.num,0) snum,p.*")
            ->where('isUP = 1 and isDelete = 2')
            ->select();
        //组合列表
        $productList = array();
        foreach ($products as $product) {
            $newProduct = array($product["id"] => array(
                'id' => $product["id"],
                'name' => $product["name"],
                'img' => $product['img'],
                'price' => $product['price'],
                'price1' => $product['price1'],
                'price2' => $product['price2'],
                'price3' => $product['price3'],
                'price4' => $product['price4'],
                'price5' => $product['price5'],
                'price6' => $product['price6'],
                'price7' => $product['price7'],
                'price8' => $product['price8'],
                'price9' => $product['price9'],
                'price10' => $product['price10'],
                'deductible' => $product['deductible'],
                'bonus' => $product['bonus'],
                'bonus2' => $product['bonus2'],
                'introduce' => $product['introduce'],
                'boxnum' => $product['boxnum'],
                'myprice' => $product['price' . $level],
                'prozong' => 0,
                'snum' => $product['snum'],
                'agenid' => $product['agenId'],
                'sid' => $product['sid'],
                'num' => 0
            ));
            foreach ($newProduct as $key => $value) {
                $productList[$key] = $value;
            }
        }
        $this->ajaxSuccess($productList);
    }

    // 准备确认下单页面
    public function getAddressAndProductInfo()
    {
        $id = I('get.id');
        $num = I('get.num');
        $product = M('product')->where("id=$id")->find();
        if (empty($product)) {
            $this->ajaxError("此商品不存在");
        }

        $agenId = parent::getagenAccountId();

        $stock = M('agenstock')->where("agenId = $agenId and productId = $id")->find();
        if (empty($stock) || $stock['num'] < $num) {
            $this->ajaxError("库存不足，请先补货");
        }
        $agenAddress = M('agenaddress')
            ->alias('a')
            ->join("left join region r on a.regionId = r.id")
            ->where("agenId = $agenId and isDefault = 1 and isDelete = 2")
            ->field('a.*,r.name_path namepath')
            ->find();
        if (empty($agenAddress)) {
            $agenAddress['address'] = "请设置默认收货地址";
        }
        $this->ajaxSuccess(array('num' => $num, 'product' => $product, 'address' => $agenAddress));
    }

    function getAgenTuiGuangUrl()
    {
        $agen = parent::getagenAccount();
        if (empty($agen['agenno'])) {
            $this->ajaxError("你还没有编码，请联系分公司申请推广编码");
        }
        $url = "http://" . $_SERVER['HTTP_HOST'] . "/index.php/Home/index/agenregister?id=" . $agen['agenno'];
        $this->ajaxSuccess(array('url' => $url));
    }

}
